#include "../lib/query.hpp"

#include <stdint.h>

Query::Query()
{
    this->key = "";
}

Query::Query(std::string key, RoutingIndex index, timeval start)
{
    this->key = key;
    std::vector<std::string> sub = index.getSubscriber(key);
    this->start = start;
    struct timeval tv;
    tv.tv_sec = 0;
    tv.tv_usec = 0;
    for(unsigned int i = 0; i< sub.size(); i++)
    {
        this->subscribers[sub[i]] = tv;
    }
    state = WINDOW;
}

struct timeval Query::latestAck()
{
    std::map<std::string, struct timeval>::iterator iter;
    int64_t ret = 0;
    for(iter =  subscribers.begin(); iter != subscribers.end(); ++iter)
    {
        int64_t usec = timeval_to_usec(&(iter->second));
        if(ret == 0)
            ret = usec;
        else if(ret < usec)
            ret = usec;
    }
    timeval tv;
    usec_to_timeval(ret,&tv);
    return tv;
}

int64_t Query::windowFrom(struct timeval end)
{
    int64_t ustart = timeval_to_usec(&start);
    int64_t ufinish = timeval_to_usec(&end);
    int64_t udifference = ufinish - ustart;
    return udifference;
}

bool Query::allAckRecieved()
{
    std::map<std::string, struct timeval>::iterator iter;
    for(iter =  subscribers.begin(); iter != subscribers.end(); ++iter)
    {
        if(timeval_to_usec(&(iter->second)) == 0)
            return false;
    }
    return true;
}
